package cn.xqj.user.service.impl;

import cn.xqj.basic.exception.BusinessException;
import cn.xqj.basic.service.impl.BaseServiceImpl;
import cn.xqj.basic.util.MD5Utils;
import cn.xqj.basic.util.StrUtils;
import cn.xqj.user.domain.Logininfo;
import cn.xqj.user.domain.User;
import cn.xqj.user.dto.EmailUserDto;
import cn.xqj.user.dto.UserDto;
import cn.xqj.user.mapper.LogininfoMapper;
import cn.xqj.user.mapper.UserMapper;
import cn.xqj.user.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.mail.internet.MimeMessage;


@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private JavaMailSender javaMailSender;





    @Override
    @Transactional
    public void add(User user) {
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        user.setPassword(MD5Utils.encrypByMd5(user.getPassword() + salt));
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.add(logininfo);
        user.setLogininfo_id(logininfo.getId());
        userMapper.add(user);
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        return logininfo;
    }


    @Override
    @Transactional
    public void update(User user) {
        Long logininfo_id = user.getLogininfo_id();
        Logininfo logininfo = logininfoMapper.findOne(user.getLogininfo_id());
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setId(logininfo_id);
        logininfoMapper.update(logininfo);
        userMapper.update(user);

    }

    @Override
    public void del(Long id) {
        User user = userMapper.findOne(id);
        logininfoMapper.del(user.getLogininfo_id());
        super.del(id);
    }

    @Override
    public void phoneRegiser(UserDto userDto) {

        String inputSmsCode = userDto.getInputSmsCode();
        String password = userDto.getPassword();
        String repeatPassword = userDto.getRepeatPassword();
        String phone = userDto.getPhone();

        if (StringUtils.isEmpty(inputSmsCode)) {
            throw new BusinessException("短信验证码为空！");
        }

        if (StringUtils.isEmpty(phone)) {
            throw new BusinessException("电话号码为空！");
        }

        if (StringUtils.isEmpty(password)) {
            throw new BusinessException("密码为空！");
        }

        if (StringUtils.isEmpty(repeatPassword)) {
            throw new BusinessException("二次输入密码为空！");
        }

        if (!password.trim().equals(repeatPassword.trim())) {
            throw new BusinessException("两次密码不一致");
        }

        Object redisPhoneCode = redisTemplate.opsForValue().get("register:" + phone);

        if (redisPhoneCode == null) {
            throw new BusinessException("短信验证码已过期！");
        }

        if (!redisPhoneCode.toString().split(":")[0].equals(inputSmsCode.trim())) {
            throw new BusinessException("短信验证码错误！");
        }

        Logininfo logininfo = userDto2Logininfo(userDto);
        User user = logininfo2User(logininfo);

        logininfoMapper.add(logininfo);
        Long logininfoId = logininfo.getId();


        user.setLogininfo_id(logininfoId);
        userMapper.add(user);

    }

    @Override
    public void emailRegiser(EmailUserDto emailUserDto) {
        String email = emailUserDto.getEmail();
        String password = emailUserDto.getPassword();
        String repeatPasswod = emailUserDto.getRepeatPassword();

        if (StringUtils.isEmpty(email)) {
            throw new BusinessException("邮箱地址为空");
        }

        if (StringUtils.isEmpty(password)) {
            throw new BusinessException("密码为空");
        }

        if (StringUtils.isEmpty(repeatPasswod)) {
            throw new BusinessException("二次密码为空");
        }

        if (!password.trim().equals(repeatPasswod.trim())) {
            throw new BusinessException("两次密码不一致");
        }

        if (logininfoMapper.findByEmail(emailUserDto.getEmail().trim()) != null) {
            throw new BusinessException("此邮箱已注册，请更换邮箱！");
        }

        Logininfo logininfo = emailUserDto2Logininfo(emailUserDto);

        logininfoMapper.add(logininfo);

        Long logininfoId = logininfo.getId();

        User user = logininfo2User(logininfo);

        user.setLogininfo_id(logininfoId);

        userMapper.add(user);

        //复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            //使用工具类来构建消息
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            //发送方
            helper.setFrom("715184003@qq.com");
            //设置邮件主题
            helper.setSubject("账号激活通知");
            //邮件正文
            helper.setText("<h1>账号激活</h1><br>"+
                    "<span>点击下面的激活链接激活账号<br>"+
                    "<a href='http://127.0.0.1:8080/logininfo/active/"+logininfoId+"'>点击激活</a>",true);
            //helper.setTo(manager.getEmail()); - 以后发给店铺入驻时的邮箱
            helper.setTo("715184003@qq.com"); //这里用我自己的邮箱做测试
            //发送消息
            javaMailSender.send(mimeMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }



    private Logininfo emailUserDto2Logininfo(EmailUserDto emailUserDto) {
        Logininfo logininfo = new Logininfo();
        logininfo.setUsername(emailUserDto.getEmail());
        logininfo.setEmail(emailUserDto.getEmail());
        String salt = StrUtils.getComplexRandomString(32);
        logininfo.setSalt(salt);
        logininfo.setPassword(MD5Utils.encrypByMd5(emailUserDto.getPassword() + salt));
        logininfo.setType(1);
        logininfo.setDisable(false);
        return logininfo;
    }

    private User logininfo2User(Logininfo logininfo) {
        User user = new User();
        BeanUtils.copyProperties(logininfo,user);
        return user;
    }

    private Logininfo userDto2Logininfo(UserDto userDto) {
        Logininfo logininfo = new Logininfo();
        logininfo.setUsername(userDto.getPhone().trim());
        logininfo.setPhone(userDto.getPhone().trim());
        String salt = StrUtils.getComplexRandomString(32);
        logininfo.setSalt(salt);
        logininfo.setPassword(MD5Utils.encrypByMd5(userDto.getPassword() + salt));
        return logininfo;
    }
}
